<?php
// +----------------------------------------------------------------------
// | Site:  [ http://www.yzmcms.com]
// +----------------------------------------------------------------------
// | Copyright: 袁志蒙工作室，并保留所有权利
// +----------------------------------------------------------------------
// | Author: YuanZhiMeng <214243830@qq.com>
// +---------------------------------------------------------------------- 
// | Explain: 这不是一个自由软件,您只能在不用于商业目的的前提下对程序代码进行修改和使用，不允许对程序代码以任何形式任何目的的再发布！
// +----------------------------------------------------------------------

defined('IN_YZMPHP') or exit('Access Denied'); 
yzm_base::load_controller('common', 'admin', 0);
yzm_base::load_sys_class('page','',0);
yzm_base::load_common('class/jst.class.php');
yzm_base::load_common('class/xlswriter.class.php');

class jst_admin extends common {

	/**
	 * 配置信息
	 */

	public $config=[];
	public $jst=[];
	public $jst_arr=[];
	public $data=[];
	
	public function __construct(){
		//聚水潭列表
		$this->jst = get_jst_list();
		$k = 0;
		foreach($this->jst as $v){
			$this->jst_arr[$k]['id'] = $v['id'];
			$this->jst_arr[$k]['title'] = $v['short_name'];
			$k++;
		}
		parent::__construct();
	}
	
	//系统信息
	public function init() {
		include $this->admin_tpl('jst_admin/jst_admin');
	}
	
	//统计看板
	public function jst_compass(){
		//后台通知
		$notice = get_config('admin_notice');
		//授权即将过期提醒
		$arr = get_jst_list();
		foreach($arr as $k=>$v){
			$expires_in = $v['expires_in'];
			if($expires_in<time()+15*86400){
				$notice =$v['short_name'].'聚水潭'.date('Y-m-d H:i:s',$expires_in).'过期，请及时授权<br/>';
			}
		}
		include $this->admin_tpl('jst_admin/jst_compass');
	}
	
	//统计库存、销量
	public function public_inventory(){
		//分类
		$ys_brand = get_brand_list_ys();
		$ts_brand = ['唐狮','天钧新塘仓','法派FAPAI'];
		$ys_shop = get_shop_list_ys();
		$is_clear = $_GET['clear']??0;
		if($is_clear){
			delete_all('stat_inventory*');
			delete_all('stat_order_day*');
		}
		//库存统计
		$brands = get_brand_list();
		$inventorys_info = getcache('stat_inventory')?getcache('stat_inventory'):[];
		$ys_inventorys_info = getcache('stat_inventory_ys')?getcache('stat_inventory_ys'):[];
		$ts_inventorys_info = getcache('stat_inventory_ts')?getcache('stat_inventory_ts'):[];
		$time = getcache('stat_inventory_time');
		if(empty($ys_inventorys_info)){
			foreach($brands as $k=>$v){
				$qty = D('jst_inventorys')->alias('i')->field('sum(qty)')->join(C('db_prefix').'jst_sku s on i.sku_id = s.sku_id','left')->where(['s.brand'=>$v])->one();
				$qty = $qty?$qty:0;
				if(in_array($v,$ys_brand)){
					$ys_inventorys_info[$k]['brand'] = $v;
					$ys_inventorys_info[$k]['qty'] = $qty;
					continue;
				}
				if(in_array($v,$ts_brand)){
					$ts_inventorys_info[$k]['brand'] = $v;
					$ts_inventorys_info[$k]['qty'] = $qty;
					continue;
				}
				$inventorys_info[$k]['brand'] = $v;
				$inventorys_info[$k]['qty'] = $qty;
			}
			setcache('stat_inventory',$inventorys_info,30*60);
			setcache('stat_inventory_ys',$ys_inventorys_info,30*60);
			setcache('stat_inventory_ts',$ts_inventorys_info,30*60);
			setcache('stat_inventory_time',time(),30*60);
			$time = time();
		}

		
		//订单统计
		$ys_supplier_name = [];
		$other_supplier_name = ['唐狮00','法派222','常熟吉普','濮院吉普','佐佑吉普','常熟衣品天成'];
		$other_orders_info =  getcache('stat_order_day_other')?getcache('stat_order_day_other'):[];
		$ys_orders_info = getcache('stat_order_day_ys')?getcache('stat_order_day_ys'):[];
		$orders_info_title = getcache('stat_order_day_title')?getcache('stat_order_day_title'):'';
		if(empty($ys_orders_info)){
			//晚上9点后统计今天发货数据
			if(date('His')>210000){
				$orders_info_title = '今天发货';
				$start = strtotime(date('Y-m-d'));
				$end = time();
				$expires_in = $start+86400-time();
			}else{
				$orders_info_title = '昨日发货';
				$start = strtotime('yesterday');
				$end = $start+86400;
				$expires_in = strtotime(date('Y-m-d').' 21:00:00')-time();
			}
			$where ='1=1 and o.send_date>'.$start.' and o.send_date<='.$end;
			$where .=' and o.status_code=9';
			$list = D('jst_orders')->alias('o')->field('sum(o.qty) qty,s.supplier_name')->join(C('db_prefix').'jst_sku s on s.sku_id=o.sku_id','left')->where($where)->group('s.supplier_name')->select();
			$bh_list = D('jst_orders')->alias('o')->field('sum(o.qty) qty,s.supplier_name')->join(C('db_prefix').'jst_sku s on s.sku_id=o.sku_id','left')->where($where.' and so_id like "BHPICK-%"')->group('s.supplier_name')->select();
			foreach($list as $k=>$v){
				$bh_qty = 0;
				foreach($bh_list as $key=>$val){
					if($val['supplier_name']==$v['supplier_name']){
						$bh_qty = $val['qty'];
						unset($bh_list[$k]);
					}
				}
				if(in_array($v['supplier_name'],$other_supplier_name)){
					$other_orders_info[$k]['supplier_name'] = $v['supplier_name'];
					$other_orders_info[$k]['qty'] = $v['qty']-$bh_qty;
					$other_orders_info[$k]['bh_qty'] = $bh_qty;
				}else{
					$ys_orders_info[$k]['supplier_name'] = $v['supplier_name'];
					$ys_orders_info[$k]['qty'] = $v['qty']-$bh_qty;
					$ys_orders_info[$k]['bh_qty'] = $bh_qty;
				}
			}
			setcache('stat_order_day_other',$other_orders_info,$expires_in);
			setcache('stat_order_day_ys',$ys_orders_info,$expires_in);
			setcache('stat_inventory_time',time(),$expires_in);
			setcache('stat_order_day_title',$orders_info_title,$expires_in);
			$time = time();
		}
		include $this->admin_tpl('jst_admin/jst_public_inventory');
	}
	
	//订单流入
	public function public_orders(){
		$shop_id = $_GET['shop_id']??0;
		$is_ys = $_GET['is_ys']??0;
		$is_clear = $_GET['clear']??0;
		$where = '1=1';
		if($shop_id){
			$where .=" AND o.shop_id=".$shop_id;
		}
		if($is_clear){
			delete_all('stat_orders*');
		}
		if($is_ys){
			$shop_ids = implode(',',get_shop_list_ys());
			$where = ' o.shop_id in ('.$shop_ids.')';
		}
		$end = strtotime(date('Y-m-d'));
		$start = $end - 86400;
		$data1 = [];
		$data2 = [];
		$data3 = [];
		for($i=0;$i<48;$i++){
			$h = intval($i/2)<10 ? '0'.intval($i/2) : intval($i/2);
			$m = $i%2==0 ? '00' : '30';
			$hm = $h.':'.$m;
			if(intval(date('Hm'))>$h.$m){
				$data1[$hm] = 0;
			}else{
				$data1[$hm] = '';
			}
			$data2[$hm] = 0;
			$data3[$hm] = 0;
		}
		//今天
		$where1 = $where.' AND o.order_date>='.$end.' AND substring_index(o.order_from,",",1)<>"vip"';
		//昨天
		$where2 = $where.' AND o.order_date>='.$start.' AND o.order_date<'.$end.' AND substring_index(o.order_from,",",1)<>"vip"';
		//前天
		$where3 = $where.' AND o.order_date>='.($start-86400).' AND o.order_date<'.$start.' AND substring_index(o.order_from,",",1)<>"vip"';
		$group = '1800*floor(o.order_date/1800)';
		$field = "FROM_UNIXTIME( ".$group.",'%H:%i') time ";
		//今天
		$list1 = D('jst_orders')->alias('o')->field("sum(o.qty ) qty,".$field)->where($where1)->group($group)->order('o.order_date asc')->limit(48)->select();
		//昨天
		$list2 = getcache('stat_orders2_'.$shop_id.'_'.$is_ys);
		if(!$list2){
			$list2 = D('jst_orders')->alias('o')->field("sum(o.qty ) qty,".$field)->where($where2)->group($group)->order('o.order_date asc')->limit(48)->select();
			$time = strtotime(date('Y-m-d'))+86400-time();
			setcache('stat_orders2_'.$shop_id.'_'.$is_ys,$list2,$time);
		}
		//前天
		$list3 = getcache('stat_orders3_'.$shop_id.'_'.$is_ys);
		if(!$list3){
			$list3 = D('jst_orders')->alias('o')->field("sum(o.qty ) qty,".$field)->where($where3)->group($group)->order('o.order_date asc')->limit(48)->select();
			$time = strtotime(date('Y-m-d'))+86400-time();
			setcache('stat_orders3_'.$shop_id.'_'.$is_ys,$list3,$time);
		}
		foreach($list1 as $v1){
			if($v1['qty']){
				$data1[$v1['time']] = $v1['qty'];
			}
		}
		foreach($list2 as $v2){
			if($v2['qty']){
				$data2[$v2['time']] = $v2['qty'];
			}
		}
		foreach($list3 as $v3){
			if($v3['qty']){
				$data3[$v3['time']] = $v3['qty'];
			}
		}
		$data2["24:00"] = $data2["00:00"];
		$data3["24:00"] = $data3["00:00"];
		$data = ['date'=>array_keys($data2),'qty1'=>array_values($data1),'qty2'=>array_values($data2),'qty3'=>array_values($data3)];
		return_json($data);
	}
	
	//订单发货统计
	public function public_trend(){
		$shop_id = $_GET['shop_id']??0;
		$days = $_GET['days']??7;
		$is_ys = $_GET['is_ys']??0;
		$is_clear = $_GET['clear']??0;
		$where = '1=1';
		if($shop_id){
			$where .=" AND shop_id=".$shop_id;
		}
		if($is_clear){
			delete_all('stat_trend*');
		}
		//佑晟店铺
		if($is_ys){
			$shop_ids = implode(',',get_shop_list_ys());
			$where = ' shop_id in ('.$shop_ids.')';
		}
		$days = isset($_GET['days']) ? $_GET['days'] : 7;
		$end = strtotime(date('Y-m-d',time()));
		$start = $end - 86400*$days;
		$where .=' AND send_date>'.$start.' AND status_code=9';
		$list = getcache('stat_trend_'.$shop_id.'_'.$days.'_'.$is_ys);
		if(!$list){
			$list = D('jst_orders')->field("sum(qty ) qty,FROM_UNIXTIME( send_date, '%m-%d' ) date ")->where($where)->group("FROM_UNIXTIME( send_date, '%Y-%m-%d' )")->select();
			setcache('stat_trend_'.$shop_id.'_'.$days.'_'.$is_ys,$list,600);
		}
		$data = ['date'=>[],'qty'=>[]];
		if($list){
			$data = ['date'=>array_column($list,'date'),'qty'=>array_column($list,'qty')];
		}
		return_json($data);
	}
	
	//打开错误日记
	public function public_open_log(){
		$file = YZMPHP_PATH.'cache/error_log.php';
		echo nl2br(file_get_contents($file));
	}
	
	//统计商品销量排行
	public function public_sale(){
		$brand = $_GET['brand']??0;
		$days = $_GET['days']??1;
		$page_get = $_GET['page']??1;
		$is_ys = $_GET['is_ys']??0;
		$is_clear = $_GET['clear']??0;
		$where = '1=1';
		if($brand){
			$where .= " AND brand='{$brand}'";
		}
		if($is_ys){
			$brand_ys = implode(',',get_brand_list_ys());
			$brand_ys = str_replace(',','","',$brand_ys);
			$where .= ' AND brand in("'.$brand_ys.'")';
		}
		if($is_clear){
			delete_all('stat_sale*');
		}
		$order = 'sum('.$days.'days) DESC';
		$total = 100;
		$num = 15;
		$page = new page($total, $num);
		$data = getcache('stat_sale_'.$brand.'_'.$days.'_'.$page_get.'_'.$is_ys);
		if(!$data){
			$data = D('jst_sku_sales')->field('i_id,name,brand,pic,substring_index(properties_value,";",1) color,sum(1days) sum_1days,sum(3days) sum_3days,sum(7days) sum_7days,sum(30days) sum_30days,labels_brand')
			->where($where)->limit($page->limit())->group('CONCAT(i_id,substring_index(properties_value,";",1))')->order($order)->select();
			$time = strtotime(date('Y-m-d'))+86400-time();
			setcache('stat_sale_'.$brand.'_'.$days.'_'.$page_get.'_'.$is_ys,$data,$time);
		}
		$i = 1;
		foreach($data as &$v){
			$v['id'] = ($page_get-1)*$num+$i;
			$v['qty'] = $v['sum_'.$days.'days'];
			//趋势
			$v['trend'] = avg_trend($v['sum_3days']/3,$v['sum_7days']/7);
			$i++;
		}
		include $this->admin_tpl('jst_admin/jst_public_sale');
	}
	
	//统计款趋势
	public function trend(){
		$type = isset($_GET['type']) ? $_GET['type'] : '';
		$kuan = isset($_GET['kuan']) ? $_GET['kuan'] : '';
		if(!$kuan || !$type){
			exit('参数错误！');
		}
		$days = isset($_GET['days']) ? $_GET['days'] : 7;
		$end = strtotime(date('Y-m-d',time()));
		$start = $end - 86400*$days;
		if($type == 'i_id'){
			$list = D('jst_orders')->field("FROM_UNIXTIME(order_date, '%m-%d') date, sum( qty ) qty, order_date, CONCAT(i_id,substring_index(properties_value,';',1))")->where("CONCAT(i_id,substring_index(properties_value,';',1)) = '".$kuan."' AND status_code in (2,4,7,8,9) AND order_date>".$start)->limit($days)->order("order_date ASC")->group("FROM_UNIXTIME(order_date,'%Y-%m-%d')")->select();
		}else if($type == 'other_2'){
			$brand_ys = implode(',',get_brand_list_ys());
			$brand_ys = str_replace(',','","',$brand_ys);
			$where = 's.brand in("'.$brand_ys.'")';
			$list = D('jst_sku')->alias('s')
				->field("FROM_UNIXTIME(oi.order_date,'%m-%d') date,sum(oi.qty) qty,substring_index(s.other_2,'#',1) kuanhao")
				->join(C('db_prefix').'jst_orders oi ON oi.sku_id=s.sku_id', 'left')
				->where($where." and substring_index(s.other_2,'#',1) = '".$kuan."' AND status_code in (2,4,7,8,9) AND order_date>".$start)
				->limit($days)
				->order("oi.order_date ASC")
				->group("FROM_UNIXTIME(oi.order_date,'%Y-%m-%d')")
				->select();
		}

		$data = [];
		$dates = [];
		for($i=$days;$i>0;$i--){
			$date = date('m-d',$end-86400*$i);
			$data[$date] = 0;
			$dates[] = $date; 
		}
		foreach($list as $v){
			if(in_array($v['date'],$dates)){
				$data[$v['date']] = $v['qty'];
			}
		}
		$qty = json_encode(array_values($data));
		$data = json_encode(array_keys($data));
		
		include $this->admin_tpl('jst_admin/jst_trend');
		return;	
	}
	
	//聚水潭公司列表
	public function jst_list(){
		$data = D('jst_list')->select();
		foreach($data as &$v){
			if($v['status']==1){
				$jst = new jst($v['id']);
				$v['url'] = $jst->auth();
			}else{
				$v['url'] = '';
			}
		}
		include $this->admin_tpl('jst_admin/jst_list');
	}
	
	public function jst_delete() {
		D('jst_list')->delete(array('id'=>$_GET['id'])); //删除TAG内容
		delcache('jst_list');
		return_json(array('status'=>1,'message'=>L('operation_success')));
	}
	//添加聚水潭
	public function jst_add(){
		$id = input('get.id');
		$where = [];
		$data = [
			'id'=>'',
			'company'=>'',
			'short_name'=>'',
			'app_key'=>'',
			'app_secret'=>'',
			'is_ziyou'=>0,
			'start_time'=>'',
			'access_token'=>'',
			'refresh_token'=>'',
			'status'=>1
		];
		if($id){
			$where['id'] = $id;
			$data = D('jst_list')->where($where)->find();
		}
		include $this->admin_tpl('jst_admin/jst_add');
	}
	
	//店铺列表
	public function shop_list(){
		get_brand_list();
		$d = D('jst_shop');
		$type = $_GET['type'] ?? '';

		//添加或者编辑
		if($type=='add'){
			if(is_post()){
				if($_POST['id']){
					$result = $d->update($_POST,['id'=>$_POST['id']]);
				}else{
					$result = $d->insert($_POST);
				}
				if($result!==false){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}
			if($_GET['id']){
				$data = $d->where(['id'=>$_GET['id']])->find();
				$data['jst_name'] = $this->jst[$data['jst_id']]['short_name'];
			}
			include $this->admin_tpl('jst_admin/shop_add');
			exit;
		}
		
		$page = input('get.page');
		$limit = input('get.limit');
		$of = input('get.field') ? input('get.field') : 'id';
		$or = input('get.order') ? input('get.order') : 'desc';
		$shop_name = trim(input('get.shop_name'));
		$where = '1=1';
		if($shop_name){
			$where .=' AND shop_name like "%'.$shop_name.'%"';
		}
		if($page){
			$total = $d->where($where)->total();
			$page = new page($total, $limit);
			$this->data = $d->where($where)->order("$of $or")->limit($page->limit())->select();
			foreach($this->data as &$v){
				$v['jst_name'] = $this->jst[$v['jst_id']]['short_name'];
			}
			$data = ['code'=>0,'msg'=>'','count'=>$total,'data'=>$this->data];
			return_json($data);
		}
		include $this->admin_tpl('jst_admin/shop_list');
	}
	
	//品牌列表
	public function brand_list(){
		$d = D('jst_brand');
		$type = $_GET['type'] ?? '';

		//添加或者编辑
		if($type=='add'){
			if(is_post()){
				if($_POST['id']){
					$result = $d->update($_POST,['id'=>$_POST['id']]);
				}else{
					$result = $d->insert($_POST);
				}
				if($result!==false){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}
			if($_GET['id']){
				$data = $d->where(['id'=>$_GET['id']])->find();
				$data['jst_name'] = $this->jst[$data['jst_id']]['short_name'];
			}
			include $this->admin_tpl('jst_admin/brand_add');
			exit;
		}
		
		$page = input('get.page');
		$limit = input('get.limit'); 
		$of = input('get.field') ? input('get.field') : 'id';
		$or = input('get.order') ? input('get.order') : 'desc';
		$shop_name = trim(input('get.shop_name'));
		$where = '1=1';
		if($page){
			$total = $d->where($where)->total();
			$page = new page($total, $limit);
			$this->data = $d->where($where)->order("$of $or")->limit($page->limit())->select();
			foreach($this->data as &$v){
				$v['jst_name'] = $this->jst[$v['jst_id']]['short_name'];
				$v['jst_name2'] = $this->jst[$v['jst_id2']]['short_name'];
			}
			$data = ['code'=>0,'msg'=>'','count'=>$total,'data'=>$this->data];
			return_json($data);
		}
		include $this->admin_tpl('jst_admin/brand_list');
	}
	
	//接口请求日记
	public function jst_log(){
		$d = D('jst_log');
		if(!$log_type = getcache('JST_CONFIG::log_type')){
			$log_type = $d->field('type')->group('type')->select();
			$log_type =array_column($log_type,'type');
			setcache('JST_CONFIG::log_type', $log_type,86400);
		}
		$page = input('get.page');
		$limit = input('get.limit');
		$of = input('get.field') ? input('get.field') : 'id';
		$or = input('get.order') ? input('get.order') : 'desc';
		$status = input('get.status') ?? '';
		$type = input('get.type') ?? '';
		$start = isset($_GET["start"]) ? $_GET["start"] : date("Y-m-d",strtotime("-7 day"));
		$end = isset($_GET["end"]) ? $_GET["end"] : date('Y-m-d');
		$jst_id = input('get.jst_id') ?? '';
		$shop_id = isset($_GET["shop_id"]) ? $_GET["shop_id"] : '';
		$where = '1=1';
		
		if($status!=''){
			$where .=' AND status ='.$status;
		}
		if($type){
			$where .=' AND type ="'.$type.'"';
		}
		if($start){
			$where .=' AND add_time >='.strtotime($start);
		}
		if($end){
			$where .=' AND add_time <='.strtotime($end)+86400;
		}
		if($jst_id){
			$where .=' AND jst_id ='.$jst_id;
		}
		if($shop_id){
			$shop_id = str_replace(',','","',$shop_id);
			$where .= ' AND shop_id in("'.$shop_id.'")';
		}
		$shop = get_shop_all();
		if($page){
			$total = $d->where($where)->total();
			$page = new page($total, $limit);
			$this->data = $d->where($where)->order("$of $or")->limit($page->limit())->select();
			//echo $d->lastsql();
			foreach($this->data as &$v){
				$v['jst_name'] = $this->jst[$v['jst_id']]['short_name'];
				$v['shop_name'] = '';
				if($v['shop_id']>0){
					$v['shop_name'] = $shop[$v['shop_id']]['nick'];
				} 
			}
			$data = ['code'=>0,'msg'=>'','count'=>$total,'data'=>$this->data];
			return_json($data);
		}
		include $this->admin_tpl('jst_admin/jst_log');
	}
	
	//修复工具--重新获取订单
	public function reget_order(){
		$action = $_POST['action']??'';
		if($action == 'reget_order'){
			$where = [];
			if($_POST['shop_id']){
				$where['shop_id'] = $_POST['shop_id'];
				delcache('LOCK::get_orders_'.$_POST['shop_id']);//删除缓存
			}else{
				delcache('LOCK::*');//删除缓存
			}
			$where['modified_begin > '] = strtotime($_POST['start'])-86400;
			$res = D('jst_log')->delete($where);//删除log表
			
			if($res!==false){
				return_json(array('status'=>1,'message'=>'操作成功，已在后台执行重新获取订单！'));
			}else{
				return_json(array('status'=>0,'message'=>'操作失败，请重试！'));
			}
		}
		include $this->admin_tpl('jst_admin/reget_order');
	}
	
	//修复工具--重新获取商品
	public function reget_item(){
		$action = $_POST['action']??'';
		if($action == 'reget_item'){
			$where['jst_id'] = $_POST['jst_id'];
			$where['type'] = 'item';
			$res = D('jst_log')->delete($where);//删除log表
			if($res!==false){
				return_json(array('status'=>1,'message'=>'操作成功，已在后台执行重新获取商品！'));
			}else{
				return_json(array('status'=>0,'message'=>'操作失败，请重试！'));
			}
		}
		include $this->admin_tpl('jst_admin/reget_item');
	}
	
	/*仓库列表*/
	public function wms(){
		$of = input('get.field');
		$or = input('get.order');
		$of = $of ? $of : 'id';
		$or = $or ? $or : 'ASC';
		$wms = D('jst_wms');
		$page = input('get.page');
		if($page){
			$total = $wms->total();
			$page = new page($total, 100);
			$data = $wms->order("$of $or")->limit($page->limit())->select();
			foreach($data as &$v){
				$v['jst_name'] = $this->jst[$v['jst_id']]['short_name'];
			}
			$data = ['code'=>0,'msg'=>'','count'=>$total,'data'=>$data];
			return_json($data);
		}
		include $this->admin_tpl('jst_admin/wms_list');
	}
	
	/*重新获取仓库列表*/
	public function get_wms(){
		$jst_id = $_GET['jst_id'];
		if(!$jst_id){
			return_json(['code'=>1,'msg'=>'参数错误：jst_id为空']);
		}
		$jst = new jst($jst_id);
		$result = $jst->wms();
		if($result['code'] == 0){
			foreach($result['data']['datas'] as $v){
				$arr = [
					'name' => $v['name'],
					'co_id' => $v['co_id'],
					'wms_co_id' => $v['wms_co_id'],
					'is_main' => $v['is_main']?1:0,
					'is_enable' => 0,
					'status' => $v['status'],
					'remark1' => $v['remark1'],
					'remark2' => $v['remark2'],
					'jst_id' => $jst_id
				];
				$info = D('jst_wms')->where(array('wms_co_id' => $v['wms_co_id']))->find();
				if($info){
					unset($arr['is_enable']);
					D('jst_wms')->update($arr, array('wms_co_id'=>$v['wms_co_id']));
				}else{
					D('jst_wms')->insert($arr);
				}
			}
			return_json(array('code'=>0,'msg'=>'获取成功！'));
		}else{
			return_json(array('code'=>1,'msg'=>$result['msg']));
		}
	}
	
	//采购单
	public function purchaser(){
		$of = input('post.field') ? input('post.field') : 'confirm_date';
		$or = input('post.order') ? input('post.order') : 'desc';
		$download = isset($_POST['download']) ? $_POST['download'] : 0;
		$page = input('post.page')?input('post.page'):1;
		$limit = input('post.limit')?input('post.limit'):30;
		$status = isset($_POST["status"]) ? $_POST["status"] : 'Confirmed';
		$purchaser = D('jst_purchaser');
		$page = input('get.page');
		$purchaser_items = D('jst_purchaser_items');
		$download = isset($_POST['download']) ? $_POST['download'] : 0;
		$jst_id = isset($_POST['jst_id']) ? $_POST['jst_id'] : '';
		$i_id = isset($_POST["i_id"]) ? $_POST["i_id"] : '';
		$po_id = isset($_POST["po_id"]) ? $_POST["po_id"] : '';
		$sku_id = isset($_POST["sku_id"]) ? $_POST["sku_id"] : '';
		$other_2 = isset($_POST["other_2"]) ? trim($_POST["other_2"]) : '';
		$name = isset($_POST["name"]) ? trim($_POST["name"]) : '';
		$where = '1=1';

		if(!is_post()){
			return include $this->admin_tpl('jst_admin/jst_purchaser');
		}
		if($i_id) {
			if(strpos($i_id,'*') !== false){
				$i_id = trim($i_id,'*');
				$where .= ' AND pi.i_id LIKE \'%'.$i_id.'%\'';
			}else{
				$where .= ' AND pi.i_id = "'.$i_id.'"';
			}
		}
		if($sku_id) {
			if(strpos($sku_id,'*') !== false){
				$sku_id = trim($sku_id,'*');
				$where .= ' AND pi.sku_id LIKE \'%'.$sku_id.'%\'';
			}else{
				$where .= ' AND pi.sku_id = "'.$sku_id.'"';
			}
		}
		if($other_2){
			$where .=' AND pi.other_2 LIKE \'%'.$other_2.'%\'';
		}
		if($name) {
			$where .= ' AND pi.name LIKE \'%'.$name.'%\'';
		}
		if($po_id) {
			if(strpos($po_id,',')){
				$where .= ' AND pi.po_id in('.$po_id.')';
			}else{
				$where .= ' AND pi.po_id = '.$po_id;
			}
		}
		
		if($status) {
			if($status != ''){
				$where .= ' AND p.status = "'.$status.'"';
			}
		}
		if($jst_id){
			$where .=' AND p.jst_id = '.$jst_id;
		}
		$status_arr = ['Creating'=>'草拟','WaitConfirm'=>'待审核','Confirmed'=>'已确认','Finished'=>'完成','Cancelled'=>'作废'];
		if($download==0){
			$temp = $purchaser->alias('p')->field('count(DISTINCT(p.po_id)) count')->join(C('db_prefix').'jst_purchaser_items pi on pi.po_id = p.po_id','left')->where($where)->find();
			$total = $temp['count'];
			$page = new page($total, $limit);
			$data = $purchaser->alias('p')->field('p.*,pi.name,pi.other_2')->join(C('db_prefix').'jst_purchaser_items pi on pi.po_id = p.po_id','left')->where($where)->group('pi.po_id')->limit($page->limit())->order("$of $or")->select();
			foreach($data as &$v){
				$v['jst_name'] = $this->jst[$v['jst_id']]['short_name'];
			}
			$data = ['code'=>0,'msg'=>'','count'=>$total,'data'=>$data];
			return_json($data);
		}else{
			$number = 50000;
			$page = 1;
			$excel = new xlswriter('purchaser',1);
			$data = $purchaser->alias('p')->field('p.*,pi.name')->join(C('db_prefix').'jst_purchaser_items pi on pi.po_id = p.po_id','left')->where($where)->group('pi.po_id')->order("$of $or")->select();
			foreach($data as &$v){
				$v['purchaser_status'] = $status_arr[$v['status']];
				$v['purchaser_qty'] = $v['qty'];
				$v['purchaser_remark'] = $v['remark'];
				$v['purchaser_items'] = '';
				$items = D('jst_purchaser_items')->field('other_2,qty')->where(['po_id'=>$v['po_id']])->select();
				foreach($items as $val){
					$item = explode('#',$val['other_2']);
					$v['purchaser_items'] .= $item[1].'*'.$val['qty'].' ';
				}
			}
			$excel->insert_data($data);
			unset($data);
			$url = $excel->output();
			$data = ['code'=>0,'msg'=>'','url'=>$url];
			return_json($data);
		}
	}
	/*采购商品明细*/
	public function purchaser_item(){
		$po_id = $_GET['po_id'];
		$jst_id = isset($_GET['jst_id']) ? $_GET['jst_id'] : '';
		$page = input('get.page');
		if(!$page){
			return include $this->admin_tpl('jst_admin/jst_purchaser_item');
		}
		$where = '1=1';
		if(!$po_id){
			exit('参数错误！');
		}else{
			$where .=' and po_id='.$po_id;
		}
		if($jst_id){
			//$where .=' and jst_id='.$jst_id;
		}
		$purchaser_items = D('jst_purchaser_item');
		$data = $purchaser_items->alias('pi')->field('pi.*,s.pic,s.other_2')->join('yzm_jst_sku s on s.sku_id = pi.sku_id','left')->where($where)->order('sku_id asc')->select();
		$data = ['code'=>0,'msg'=>'','count'=>1,'data'=>$data];
		return_json($data);
	}

	//已售采购建议
	public function public_suggest(){
		$db = D('jst_inventorys');
		//$brands_shops = ['增致牛仔 ZENGZHI'=>11736347,'东方骆驼'=>15838046,'唐狮'=>12313808,'安瑞井'=>13405608,'法派FAPAI'=>[13362519,12627770],'琴曼'=>14013626,'米菲 MIFFY'=>11760100,'美丽衣橱'=>13527044,'雅鹿'=>12853531];
		//所有品牌缺货数
		$list = getcache('stat_suggest');
		//if($list){
			$sql = 'select sum(a) total_qty,brand from (SELECT qty-order_lock as a,brand FROM yzm_jst_inventorys where brand in("增致牛仔 ZENGZHI","法派FAPAI","JEEP","东方骆驼","衣品天成") HAVING a<0) i GROUP BY brand';
			$list = $db->fetch_all($db->query($sql));
			setcache('stat_suggest',$list,60*10);
		//}
		$data = [];
		foreach($list as $v){
			/*
			//法派进货仓缺货
			if($v['brand'] == '法派FAPAI'){
				$result = getcache('stat_suggest_法派FAPAI');
				if(!$result){
					$sql = 'SELECT sum(a) gx_qty FROM (SELECT i.qty - i.order_lock AS a,i.sku_id FROM yzm_jst_inventorys i WHERE	(i.brand = "法派FAPAI" ) and i.other_2 LIKE "%订做%" HAVING	a < 0) c';
					$result = $db->fetch_array($db->query($sql));
					setcache('stat_suggest_法派FAPAI',$result,60*10);
				}
			}elseif($v['brand'] == 'JEEP'){//JEEP半成品缺货
				$result = getcache('stat_suggest_JEEP');
				if(!$result){
					$sql = 'SELECT sum(a) gx_qty  FROM ( SELECT i.qty - i.order_lock AS a, i.sku_id FROM yzm_jst_inventorys i INNER JOIN yzm_jst_inventorys it ON i.other_2 = it.other_2 WHERE ( i.brand = "JEEP" )  AND it.brand = "JEEP半成品" HAVING a < 0) c';
					$result = $db->fetch_array($db->query($sql));
					setcache('stat_suggest_JEEP',$result,60*10);
				}
			}else{
				$result = getcache('stat_suggest_'.$v['brand']);
				//共享仓缺货
				if(!$result){
					$sql = 'SELECT sum(a) gx_qty  FROM ( SELECT i.qty - i.order_lock AS a, i.sku_id FROM yzm_jst_inventorys i INNER JOIN yzm_jst_inventorys it ON i.other_2 = it.other_2 WHERE ( i.brand = "'.$v['brand'].'" )  AND it.brand = "佑晟共享仓"'.' HAVING a < 0) c';
					$result = $db->fetch_array($db->query($sql));
					setcache('stat_suggest_'.$v['brand'],$result,60*10);
				}
			}
			$v['gx_qty'] = $result['gx_qty'];
			*/
			//采购途中
			$sql = 'SELECT sum( purchase_qty ) purchase_qty,sum(a) wait_purchase_qty FROM (SELECT i.qty - i.order_lock AS a,i.sku_id,purchase_qty FROM yzm_jst_inventorys i WHERE ( i.brand = "'.$v['brand'].'" ) HAVING a < 0 ) c';
			$result = $db->fetch_array($db->query($sql));
			$v['purchase_qty'] = $result[0]['purchase_qty']??0;
			
			
			$sql = 'SELECT sum(a) wait_purchase_qty FROM (SELECT i.qty - i.order_lock+purchase_qty AS a,i.sku_id,purchase_qty FROM yzm_jst_inventorys i WHERE ( i.brand = "'.$v['brand'].'" ) HAVING a < 0 ) c';
			$result = $db->fetch_array($db->query($sql));
			
			$v['wait_purchase_qty'] = $result[0]['wait_purchase_qty']??0;
			
			if($v['brand'] != '佑晟共享仓'){
				$data[] = $v;
			}
			//今日发货统计
			/*
			$shop_ids = $brands_shops[$v['brand']];
			if(!is_array($shop_ids)){
				$where = 'o.shop_id = '.$shop_ids;
			}else{
				$where = 'o.shop_id in ('.implode($shop_ids,',').')';
			}
			$start = strtotime(date('Ymd'));
			$where .=' and o.send_date>'.$start.' and o.send_date<='.$start+86400;
			$where .=' and o.status="Sent"';
			$qty = D('jst_orders')->alias('o')
				->field('sum(oi.qty) qty')
				->where($where)
				->join('yzmcms_jst_orders_items oi ON o.o_id=oi.o_id and o.shop_id = oi.shop_id', 'left')
				->one();
			$v['qty'] = $qty?$qty:0;*/
		}
		include $this->admin_tpl('jst_admin/jst_public_suggest');
	}


	/*入库记录*/
	public function purchaser_log(){
		$page = input('get.page');
		if($page){
			$po_id = input('get.po_id');
			$jst_id = input('get.jst_id');
			$jst = new jst($jst_id);
			$arr = [
				'po_ids' => [$_GET['po_id']],
				"page_index" => 1,
				"page_size" => 50
			];
			$result = $jst->purchasein($arr);
			$data = $result['data']['datas'];
			$count = $result['data']['data_count'];
			if($count>1){
				for($i=2;$i>=$count;$count++){
					$arr = [
						'po_ids' => [$_GET['po_id']],
						"page_index" => $i,
						"page_size" => 50
					];
					$result = $jst->purchasein($arr);
					$data = array_merge($data,$result['data']['datas']);
				}
			}
			$return_data = [];
			$wh_id_arr=['','主仓','销退仓','进货仓','次品仓'];
			foreach($data as $v){
				$return['io_id'] = $v['io_id'];
				$return['io_date'] = $v['io_date'];
				$return['wh_id'] = $wh_id_arr[$v['wh_id']];
				$return['creator_name'] = $v['creator_name'];
				foreach($v['items'] as $val){
					$return['sku_id'] = $val['sku_id'];
					$return['name'] = $val['name'];
					$return['qty'] = $val['qty'];
					$return_data[] = $return;
				}
			}
			$data = ['code'=>0,'msg'=>'','count'=>$count,'data'=>$return_data];
			return_json($data);
		}
		include $this->admin_tpl('jst_admin/jst_purchaser_log');
	}
	
	//重写保存
	public function public_save(){
		if(is_post()){
			$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
			$db = $_POST['db'];
			
			//删除无用数据以免影响提交
			unset($_POST['id']);
			if(isset($_POST['dosubmit'])) unset($_POST['dosubmit']);
			unset($_POST['yzm_csrf_token']);
			unset($_POST['db']);
			
			//时间格式化
			$_POST['start_time'] = strtotime($_POST['start_time']);
			delcache('jst_list');
			if($id){
				if(D($db)->update($_POST, array('id' => $id)) !== false){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}else{
				if(D($db)->insert($_POST) !== false){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}
		}
	}
	
}